#include <iostream>
#include <vector>
#include <unistd.h>
#include <cassert>
#include <string>
#include <sys/wait.h>
static int gchanel_ = 1;

class channel
{
public:
    channel(pid_t pid, int fd) : _pid(pid), _fd(fd)
    {
        _name = "channel-" + std::to_string(gchanel_++);
    }

public:
    std::string _name;
    pid_t _pid;
    int _fd;
};

void Work()
{
    std::cout << "child  read...." << std::endl;
}

void CreateChannels(std::vector<channel> *channels, int num = 10)
{
    for (int i = 0; i < num; i++)
    {
        // 创建管道
        int pipefd[2];
        int n = pipe(pipefd);
        assert(!n);
        (void)n;

        // 创建子进程，构建单向管道
        pid_t id = fork();
        assert(id != -1);
        // 父写子读
        if (id == 0)
        {
            // 单项通道
            close(pipefd[1]);
            // TODO
            dup2(pipefd[0], 0);
            Work();
            exit(0);
        }

        // 父进程
        close(pipefd[0]);
        channels->push_back(channel(id, pipefd[1]));
    }
}
void PrintChannel(const std::vector<channel> &channels)
{
    for (const auto &c : channels)
    {
        std::cout << "name:" << c._name << ",pid:" << c._pid << ",fd:" << c._fd << std::endl;
    }
}
int main()
{
    std::vector<channel> channels;
    CreateChannels(&channels);

    PrintChannel(channels);
    sleep(1);
    // 资源清理工作
    for (int i = 0; i < channels.size(); i++)
    {
        waitpid(-1, nullptr, 0);
    }
}